package com.github.cakin.shiro.chapter24.web.shiro.filter;

import com.github.cakin.shiro.chapter24.Constants;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @className: ForceLogoutFilter
 * @description: 强制退出拦截器
 * @date: 2020/5/31
 * @author: cakin
 */
public class ForceLogoutFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed( ServletRequest request, ServletResponse response, Object mappedValue ) throws Exception {
        Session session = getSubject(request, response).getSession(false);
        if (session == null) {
            return true;
        }
        // 如果用户会话中存在 Constants.SESSION_FORCE_LOGOUT_KEY 属性，表示被管理员强制退出了
        return session.getAttribute(Constants.SESSION_FORCE_LOGOUT_KEY) == null;
    }

    @Override
    protected boolean onAccessDenied( ServletRequest request, ServletResponse response ) throws Exception {
        try {
            // 然后调用 Subject.logout() 退出，且重定向到登录页面
            getSubject(request, response).logout();
        } catch (Exception e) {
        }
        String loginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";
         // 重定向到登录页
        WebUtils.issueRedirect(request, response, loginUrl);
        return false;
    }
}
